<template>
  <div class="page-content attraction-detail">
    <!-- 页面头部 -->
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">景点详情</h1>
        <p class="text-gray-500 mt-2">查看景点的详细信息</p>
      </div>
      <div class="flex gap-3">
        <el-button type="primary" @click="editAttraction">
          <el-icon class="mr-1"><Edit /></el-icon>编辑景点
        </el-button>
        <el-button @click="goBack">
          <el-icon class="mr-1"><Back /></el-icon>返回
        </el-button>
      </div>
    </div>

    <el-skeleton :loading="isLoading" animated>
      <template #template>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="md:col-span-2">
            <el-skeleton-item variant="image" class="w-full h-300px rounded-lg" />
            <div class="flex space-x-2 mt-2">
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
            </div>
          </div>
          <div>
            <el-skeleton-item variant="h3" class="w-1/2" />
            <el-skeleton-item variant="text" class="mt-4 w-4/5" />
            <el-skeleton-item variant="text" class="mt-4 w-3/5" />
            <el-skeleton-item variant="text" class="mt-4 w-full" />
          </div>
        </div>
      </template>

      <template #default>
        <el-row :gutter="24">
          <!-- 左侧景点信息 -->
          <el-col :md="16" :sm="24">
            <el-card shadow="hover" class="mb-6 overflow-hidden border-0 rounded-lg">
              <div class="attraction-header flex justify-between items-start">
                <div>
                  <h2 class="text-xl font-semibold">{{ attraction.spotName }}</h2>
                  <div class="flex items-center mt-2">
                    <div class="text-sm text-gray-500 flex items-center mr-4">
                      <el-icon class="mr-1"><Clock /></el-icon>
                      <!-- 优先显示营业时间描述，如果没有则显示默认时间格式 -->
                      {{ attraction.timeDescription || formatOpeningHours(attraction.openStartTime, attraction.openEndTime) }}
                    </div>
                    <div class="text-sm text-gray-500 flex items-center">
                      <el-icon class="mr-1"><Calendar /></el-icon>
                      {{ formatOpenDays(attraction.openWeek) }}
                    </div>
                  </div>
                </div>
                <el-tag :type="getStatusType(attraction.operationStatus)" size="large">
                  {{ statusTextMap[attraction.operationStatus] }}
                </el-tag>
              </div>

              <!-- 景点图片 -->
              <div class="mt-4">
                <el-carousel
                  v-if="mainImages.length"
                  :interval="4000"
                  type="card"
                  height="400px"
                  :autoplay="true"
                  indicator-position="outside"
                  class="carousel-container"
                >
                  <el-carousel-item v-for="(img, index) in mainImages" :key="index">
                    <el-image
                      :src="img.path"
                      fit="cover"
                      class="w-full h-full rounded-lg object-cover"
                      @click="previewImage(index, mainImages)"
                    >
                      <template #error>
                        <div class="image-error-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </el-carousel-item>
                </el-carousel>

                <div
                  v-else
                  class="placeholder-image flex items-center justify-center bg-gray-100 h-400px rounded-lg"
                >
                  <el-icon class="text-6xl text-gray-300"><Picture /></el-icon>
                </div>

                <!-- 相册预览 -->
                <div v-if="galleryImages.length" class="image-gallery mt-4 grid grid-cols-5 gap-2">
                  <el-image
                    v-for="(img, index) in galleryImages"
                    :key="index"
                    :src="img.path"
                    fit="cover"
                    class="gallery-thumbnail cursor-pointer h-80px rounded-md border-2 border-transparent hover:border-primary transition-all"
                    @click="previewImage(index, galleryImages)"
                  />
                </div>
              </div>

              <!-- 景点介绍 -->
              <div class="mt-6">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                  <el-icon class="mr-2 text-primary"><InfoFilled /></el-icon>景点介绍
                </h3>
                <p class="text-gray-700 leading-relaxed whitespace-pre-line">{{
                  attraction.introduce
                }}</p>
              </div>

              <!-- 特色标签 -->
              <div class="mt-6" v-if="featureTags.length">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                  <el-icon class="mr-2 text-primary"><Collection /></el-icon>特色标签
                </h3>
                <div class="flex flex-wrap gap-2">
                  <el-tag
                    v-for="(tag, index) in featureTags"
                    :key="index"
                    class="px-3 py-1.5 rounded-full border-0 text-sm"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>

              <!-- 备注 -->
              <div class="mt-6" v-if="attraction.remark">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                  <el-icon class="mr-2 text-primary"><Memo /></el-icon>备注信息
                </h3>
                <p class="text-gray-700 leading-relaxed p-4 bg-gray-50 rounded-lg">{{
                  attraction.remark
                }}</p>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧信息栏 -->
          <el-col :md="8" :sm="24">
            <!-- 基本信息卡片 -->
            <el-card shadow="hover" class="mb-6 border-0 rounded-lg">
              <template #header>
                <div class="flex items-center">
                  <el-icon class="mr-2 text-primary"><Document /></el-icon>
                  <span class="font-medium">基本信息</span>
                </div>
              </template>

              <ul class="space-y-2">
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">中文名称</span>
                  <span class="text-gray-800 flex-1">{{ attraction.spotName }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                  v-if="attraction.spotEnglishName"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">英文名称</span>
                  <span class="text-gray-800 flex-1">{{ attraction.spotEnglishName }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                  v-if="attraction.spotPinyinName"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">拼音名称</span>
                  <span class="text-gray-800 flex-1">{{ attraction.spotPinyinName }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">位置</span>
                  <span class="text-gray-800 flex-1">{{ attraction.location }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">开放时间</span>
                  <span class="text-gray-800 flex-1">{{
                    formatOpeningHours(attraction.openStartTime, attraction.openEndTime)
                  }}</span>
                </li>
                <!-- 新增的营业时间字段 -->
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                  v-if="attraction.timeDescription"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">营业时间</span>
                  <span class="text-gray-800 flex-1">{{ attraction.timeDescription }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">开放周期</span>
                  <span class="text-gray-800 flex-1">{{
                    formatOpenDays(attraction.openWeek)
                  }}</span>
                </li>
                <li
                  class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200"
                  v-if="attraction.floorSpace"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">占地面积</span>
                  <span class="text-gray-800 flex-1">{{ attraction.floorSpace }} m²</span>
                </li>
                <li
                  class="flex py-3 hover:bg-gray-50 transition-colors duration-200"
                  v-if="attraction.buildData"
                >
                  <span class="w-24 text-gray-500 flex-shrink-0">建成时间</span>
                  <span class="text-gray-800 flex-1">{{
                    formatBuildDate(attraction.buildData)
                  }}</span>
                </li>
              </ul>
            </el-card>

            <!-- 二维码 -->
            <el-card shadow="hover" class="mb-6 border-0 rounded-lg overflow-hidden">
              <template #header>
                <div class="flex items-center">
                  <el-icon class="mr-2 text-primary"><Document /></el-icon>
                  <span class="font-medium">二维码</span>
                </div>
              </template>
              <div class="flex flex-col items-center p-4">
                <QrcodeVue
                  ref="qrcodeRef"
                  :value="`https://wuhansportpark.com/weixin/?id=${attractionId}&type=tourguide&detailType=1`"
                  :size="200"
                  level="H"
                  render-as="svg"
                />
                <el-button type="primary" class="mt-4" @click="downloadQRCode">
                  <el-icon class="mr-1"><Download /></el-icon>下载二维码
                </el-button>
              </div>
              </el-card>
          </el-col>
        </el-row>
      </template>
    </el-skeleton>

    <!-- 图片预览器 -->
    <el-image-viewer
      v-if="showViewer"
      :initial-index="viewerIndex"
      :url-list="viewerImages.map((img) => img.path)"
      @close="showViewer = false"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import {
    Edit,
    Back,
    Picture,
    InfoFilled,
    Document,
    Location,
    Collection,
    Clock,
    Calendar,
    Memo,
    Download
  } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { scenicScenicSpotGetScenicSpotUsingGet } from '@/api/4a/jingdi'
  import { strToArray } from '@/utils/utils'
  import QrcodeVue from 'qrcode.vue'

  const route = useRoute()
  const router = useRouter()
  const attractionId = ref(route.query.id as string)
  const isLoading = ref(true)

  // 状态映射
  const statusTextMap = {
    1: '开放中',
    2: '部分维修',
    3: '维护中',
    4: '已关闭'
  }

  // 景点信息，添加timeDescription字段
  const attraction = ref({
    id: '',
    spotName: '',
    spotEnglishName: '',
    spotPinyinName: '',
    location: '',
    locationJson: '',
    introduce: '',
    imageUrl: '',
    galleryImages: '',
    operationStatus: 1,
    openStartTime: '',
    openEndTime: '',
    openWeek: '',
    buildData: '',
    floorSpace: '',
    timeDescription: '', // 新增的营业时间字段
    featureTag: '',
    remark: ''
  })

  // 图片数据处理
  const mainImages = computed(() => {
    try {
      return JSON.parse(attraction.value.imageUrl || '[]')
    } catch (e) {
      return []
    }
  })

  const galleryImages = computed(() => {
    try {
      return JSON.parse(attraction.value.galleryImages || '[]')
    } catch (e) {
      return []
    }
  })

  // 特色标签
  const featureTags = computed(() => {
    if (!attraction.value.featureTag) return []
    return attraction.value.featureTag
      .split(',')
      .map((tag) => tag.trim())
      .filter(Boolean)
  })

  // 位置数据
  const locationData = computed(() => {
    try {
      return JSON.parse(attraction.value.locationJson || '{}')
    } catch (e) {
      return {}
    }
  })

  // 图片预览器
  const showViewer = ref(false)
  const viewerIndex = ref(0)
  const viewerImages = ref([])

  // 格式化开放时间
  const formatOpeningHours = (start, end) => {
    if (!start || !end) return '暂无开放时间'

    const formatTime = (time) => {
      const timeStr = time.toString().padStart(6, '0')
      return `${timeStr.substring(0, 2)}:${timeStr.substring(2, 4)}`
    }

    return `${formatTime(start)} - ${formatTime(end)}`
  }

  // 格式化开放周期
  const formatOpenDays = (openWeek) => {
    if (!openWeek) return '暂无开放周期'

    const dayMap = {
      1: '周一',
      2: '周二',
      3: '周三',
      4: '周四',
      5: '周五',
      6: '周六',
      7: '周日'
    }

    const days = strToArray(openWeek).map((day) => dayMap[day] || '')

    if (days.length === 7) return '周一至周日'
    if (days.includes('周六') && days.includes('周日')) {
      const weekdays = days.filter((day) => !['周六', '周日'].includes(day))
      if (
        weekdays.length === 5 &&
        ['周一', '周二', '周三', '周四', '周五'].every((day) => weekdays.includes(day))
      ) {
        return '周一至周日'
      }
    }

    return days.join('、')
  }

  // 格式化建成时间
  const formatBuildDate = (date) => {
    if (!date) return '暂无数据'

    const dateStr = date.toString().padStart(8, '0')
    return `${dateStr.substring(0, 4)}年${dateStr.substring(4, 6)}月${dateStr.substring(6, 8)}日`
  }

  // 获取状态标签类型
  const getStatusType = (status) => {
    switch (status) {
      case 1:
        return 'success'
      case 2:
        return 'warning'
      case 3:
        return 'info'
      case 4:
        return 'danger'
      default:
        return ''
    }
  }

  // 图片预览
  const previewImage = (index, images) => {
    viewerIndex.value = index
    viewerImages.value = images
    showViewer.value = true
  }

  // 编辑景点
  const editAttraction = () => {
    router.push({
      path: '/attraction/edit',
      query: { id: attractionId.value }
    })
  }

  // 返回列表
  const goBack = () => {
    router.push('/attraction/AttractionList')
  }

  // 获取景点详情
  const getAttractionDetail = async () => {
    isLoading.value = true

    try {
      const res = await scenicScenicSpotGetScenicSpotUsingGet({
        params: { scenicSpotId: attractionId.value }
      })

      if (res.code === 0 && res.data) {
        attraction.value = res.data
      } else {
        ElMessage.error(res.msg || '获取景点详情失败')
      }
    } catch (error) {
      console.error('获取景点详情失败', error)
      ElMessage.error('获取景点详情失败')
    } finally {
      isLoading.value = false
    }
  }

  const qrcodeRef = ref(null)

  // 下载二维码
  const downloadQRCode = () => {
    if (!qrcodeRef.value) return

    const svg = qrcodeRef.value.$el
    const serializer = new XMLSerializer()
    const svgStr = serializer.serializeToString(svg)
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()

    img.onload = () => {
      canvas.width = img.width
      canvas.height = img.height
      ctx?.drawImage(img, 0, 0)
      
      const link = document.createElement('a')
      link.download = `${attraction.value.spotName || '景点'}_二维码.png`
      link.href = canvas.toDataURL('image/png')
      link.click()
    }

    img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgStr)))
  }

  onMounted(() => {
    if (attractionId.value) {
      getAttractionDetail()
    } else {
      isLoading.value = false
      ElMessage.warning('未找到景点ID')
    }
  })
</script>

<style lang="scss" scoped>
  .attraction-detail {
    .gallery-thumbnail {
      object-fit: cover;
    }

    .image-error-slot {
      @apply flex justify-center items-center w-full h-full bg-gray-100 text-gray-400 text-30px;
    }

    .carousel-container {
      :deep(.el-carousel__item) {
        border-radius: 8px;
      }
    }

    .info-list {
      li {
        .info-label {
          @apply w-80px text-gray-500;
        }

        .info-value {
          @apply flex-1 text-gray-700;
        }
      }
    }
  }
</style>
